﻿#include "formmvb.h"
#include "ui_formmvb.h"
#include"Tool/qfilehelper.h"
#include"dialogsheetnameselect.h"
#include <QStandardItemModel>
#include<QString>
#include<QDebug>
#include <QScrollBar>
#include<QMessageBox>
#include <QDir>
#include <QTableWidgetItem>
#include"Tool/wordreplace.h"
#include "Common/configData.h"
FormMvb::FormMvb(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormMvb)
{
    ui->setupUi(this);
    init();
    connectAllSlots();

}

FormMvb::~FormMvb()
{
    if(_FileclientForm!=nullptr)
        delete _FileclientForm;
    delete ui;
}

void FormMvb::LoadProtocal()
{
    QString fileName= QFileHelper::FileSelect();
    if(!fileName.isEmpty())
    {
        _xlsxHelper.OpenXLSXFile(fileName);

        //选择工作表
        DialogSheetNameSelect sheetNameSel;
        sheetNameSel.setQxlsxHelper(&_xlsxHelper);
        int nresult =sheetNameSel.exec();
        if(nresult==QDialog::Rejected)
        {
            return;
        }

        //获取选择显示的内容
        QVector<QString> protocalSelect;
//        protocalSelect<<QString::fromLocal8Bit("信号名称\nFieldIdentifier");
//        protocalSelect<<QString::fromLocal8Bit("数据类型\nDatatype");
//        protocalSelect<<QString::fromLocal8Bit("端口号\nPortnumber");
//        protocalSelect<<QString::fromLocal8Bit("字节\nByte");
//        protocalSelect<<QString::fromLocal8Bit("位\nBit");
        protocalSelect<<QString::fromLocal8Bit("信号名称");
        protocalSelect<<QString::fromLocal8Bit("数据类型");
        protocalSelect<<QString::fromLocal8Bit("端口号");
        protocalSelect<<QString::fromLocal8Bit("字节");
        protocalSelect<<QString::fromLocal8Bit("位");
        _protocalData._protocalContent = protocalSelect;
        _protocalData._OCRContent = sheetNameSel.GetCheckItem();
        //读取显示数据

        _xlsxHelper.ReadAllData(_protocalData._data);

        //协议校验
        bool bContain = false;
        foreach(QString key,_protocalData._data.keys())
        {
            if(key.contains(QString::fromLocal8Bit("端口号"))){
                bContain=true;
            }
        }
        if(!bContain)
        {
            QMessageBox::information(this,"tip",QString::fromLocal8Bit("未找到端口号数据，请正确加载MVB协议。"));
            return;
        }

        _protocalData.getUsefulData();
        if(_tableViewmodel==nullptr)
        {
            _tableViewmodel =new  QStandardItemModel(ui->tableView);
        }
        _protocalData.generateOCRData(_tableViewmodel);
        ui->tableView->setModel(_tableViewmodel);
          //自适应宽度
        ui->tableView->resizeColumnsToContents();

        //协议显示
        if(_ProtocaltableViewmodel==nullptr)
        {
            _ProtocaltableViewmodel =new  QStandardItemModel(ui->tableView);
        }
        _protocalData.generateProtocalData(_ProtocaltableViewmodel);

        ui->tableView_protocal->setModel(_ProtocaltableViewmodel);
        ui->tableView_protocal->resizeColumnsToContents();

    }
}

void FormMvb::start()
{
     emit SendLogMsg(QString::fromLocal8Bit("截屏服务端地址：%1").arg(ConfigData::snapURL_MVB));
    _websocketClient->SetURL(ConfigData::snapURL);
    _websocketClient->openWebsocket();
    if(!_websocketClient->isConnected())
    {
        emit SendLogMsg(QString::fromLocal8Bit("截屏服务连接失败."));
    }

    _workStatus = START;
    _MvbTestthread.SetProtocalData(&_protocalData);
    _MvbTestthread.start();
}

void FormMvb::stop()
{


    if(_MvbTestthread.isRunning())
    {
        _MvbTestthread.Stop();
        _workStatus = STOP;
    }
    else
    {
        _MvbTestthread.SetIndex(0);
        ClearTableViewTestResult();
    }

}

void FormMvb::Pause()
{
    _workStatus = PAUSE;
    _MvbTestthread.Pause();
}

void FormMvb::Export()
{
    //缓存替换内容
    QString tempFilePath= "C:/word/temp2.docx";
    if(!QFile::exists(tempFilePath))
    {
        QMessageBox::information(nullptr,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("模板文件缺失 ")+tempFilePath);
        return;
    }

    QString strExportFile= QFileHelper::FileSave(".docx");
    if(strExportFile.isEmpty())
        return;

    QMap<QString, QString> replaceCache;
    replaceCache["time_01"] = _testResult._startTime.toString("yyMMdd-hh:mm:ss");
    replaceCache["time_02"] = _testResult._endTime.toString("yyMMdd-hh:mm:ss");

    //内容替换
    WordReplace replace;
    replace.replace(tempFilePath,strExportFile,replaceCache);
    QMessageBox::information(nullptr,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("报表导出完成 ")+strExportFile);
}

void FormMvb::init()
{
    if(_websocketClient==nullptr)
        _websocketClient = new WebsocketClient();
    connect(_websocketClient,&WebsocketClient::ReveiveImg,this,&FormMvb::OnReceiveOCRImg);
}

void FormMvb::connectAllSlots()
{
    connect(ui->btn_protocalLoad,&QPushButton::clicked,this,&FormMvb::LoadProtocal);
    connect(ui->btn_start,&QPushButton::clicked,this,&FormMvb::start);
    connect(ui->btn_stop,&QPushButton::clicked,this,&FormMvb::stop);
    connect(ui->btn_pause,&QPushButton::clicked,this,&FormMvb::Pause);
    connect(ui->btn_wordExport,&QPushButton::clicked,this,&FormMvb::Export);
    connect(ui->tableView->verticalScrollBar(), &QScrollBar::valueChanged, ui->tableView_protocal->verticalScrollBar(), &QScrollBar::setValue);
    connect(ui->tableView_protocal->verticalScrollBar(), &QScrollBar::valueChanged, ui->tableView->verticalScrollBar(), &QScrollBar::setValue);

    connect(ui->btn_test,&QPushButton::clicked,this,&FormMvb::on_btnTest_clicked);

    //线程消息交互
    connect(&_MvbTestthread,&MVBTestThread::SendProcedureMsg,this,&FormMvb::SendLogMsg);
    connect(&_MvbTestthread,&MVBTestThread::SendScreenShotMsg,this,&FormMvb::OnThreadSnap);
    connect(&_MvbTestthread,&MVBTestThread::ThreadExitMsg,this,&FormMvb::OnThreadExit);
    connect(&_MvbTestthread,&MVBTestThread::UpdateTestResult,this,&FormMvb::ShowTestResuult);

}

void FormMvb::ClearTableViewTestResult()
{
    //清除所有检测项内容
    int nRow =_tableViewmodel->rowCount();
    int nIconColumnID = _tableViewmodel->columnCount()-1;
    for (int i = 0; i < nRow; ++i)
    {
        _tableViewmodel->setItem(i,nIconColumnID,nullptr);
    }

}

void FormMvb::ShowTestResuult(const QVariant& VartestResult)
{
    _testResult =VartestResult.value<TestResult>();
    int SerialID= _testResult._nid+1;
    QString str = QString::number(SerialID )+"/"+QString::number(_testResult._count);
    ui->lable_Index->setText(str);
    ui->progressBar->setMaximum(_testResult._count);
    ui->progressBar->setValue(SerialID);

    ui->lineEdit_startTime->setText(_testResult._startTime.toString("yyMMdd-HH:mm:ss"));
    ui->lineEdit_endTime->setText(_testResult._endTime.toString("yyMMdd-HH:mm:ss"));
    ui->lineEdit_passcount->setText(QString::number(_testResult._passCount));
    ui->lineEdit_unpasscount->setText(QString::number(_testResult._unPassCount));

    //tableView更新结果
    auto item1=new QStandardItem();
    if(_testResult.TestResultCache[_testResult._nid])
    {
        item1->setIcon(QIcon(":/Icon/icon_32/zhengque.svg"));

    }
    else
    {
        item1->setIcon(QIcon(":/Icon/icon_32/error.svg"));

    }
    _tableViewmodel->setItem(_testResult._nid,_tableViewmodel->columnCount()-1,item1);


    //滑动滑块
    QScrollBar * scrollbar = ui->tableView->verticalScrollBar();
    if(scrollbar)
    {
        if(_testResult._nid<scrollbar->maximum())
        {
            if(_testResult._nid>_nShowLine)
                scrollbar->setSliderPosition(_testResult._nid-_nShowLine);
        }
        else
        {
            scrollbar->setSliderPosition(scrollbar->maximum());
        }
    }

}

#include"vmhelper.h"
void FormMvb::on_btnTest_clicked()
{
    try {
//        VMHelper vmhelper;
//        vmhelper.LoadVMSolution(QString::fromLocal8Bit("C:/hKVision/mysolution.sol"));
//        vmhelper.SetSourceImage(QString::fromLocal8Bit("C:/image/1.png"));
//        vmhelper.Run();
//        auto results =vmhelper.GetPredictResult();

//        QString strMsg;
//        for (auto it = results.cbegin(); it != results.cend(); ++it)
//        {
//            strMsg+= QString::fromLocal8Bit("%1,%2\n").arg(it.key()).arg(it.value());
//        }

//        emit SendLogMsg(strMsg);
//        auto results2 =vmhelper.GetFormatResult();

//        QString strMsg2;
//        for (auto it = results2.cbegin(); it != results2.cend(); ++it)
//        {
//            strMsg2+= QString::fromLocal8Bit("%1,%2\n").arg(it.key()).arg(it.value());
//        }
//        emit SendLogMsg(strMsg2);

    } catch (QException ex)
    {
        QMessageBox::information(this,"错误信息",ex.what());
    }

}

void FormMvb::on_btn_snap_clicked()
{
    ui->btn_snap->setEnabled(false);
    if(_websocketClient==nullptr)
        _websocketClient = new WebsocketClient();
    _websocketClient->SetURL(ConfigData::snapURL_MVB);
    emit SendLogMsg("websocket URL:"+ConfigData::snapURL_MVB);
    _websocketClient->openWebsocket();

    bool bconnect= _websocketClient->isConnected();
    if(!bconnect)
    {
        qDebug()<<QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。")<<endl;
        emit SendLogMsg(QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。"));
         ui->btn_snap->setEnabled(true);
        return ;
    }
    _bSnapOnly=true;
    _websocketClient->screenShot();

}

void FormMvb::OnThreadSnap()
{
//    emit SendLogMsg("websocket URL:"+ConfigData::snapURL_MVB);

    if(_websocketClient==nullptr)
        _websocketClient = new WebsocketClient();
    _websocketClient->SetURL(ConfigData::snapURL_MVB);
    _websocketClient->openWebsocket();

    bool bconnect= _websocketClient->isConnected();
    if(!bconnect)
    {
        qDebug()<<QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。")<<endl;
        emit SendLogMsg(QString::fromLocal8Bit("websocket连接失败,请确认截屏程序是否启动。"));
        ui->btn_snap->setEnabled(true);
        return ;
    }
    _websocketClient->screenShot();
}

void FormMvb::OnThreadExit()
{
    _websocketClient->closeWebsocket();

    //根据情况选择是否重置Id以及
    switch (_workStatus) {
    case STOP:
        _MvbTestthread.SetIndex(0);
        ClearTableViewTestResult();
        break;
    case PAUSE:

        break;
    default:
        break;
    }
}


void FormMvb::OnReceiveOCRImg(QByteArray byteArray)
{

    QPixmap pixmap;
    pixmap.loadFromData(byteArray);
    ui->scrollAreaWidgetContents->setMinimumSize( pixmap.width(), pixmap.height());
    ui->labelImgmvb->setImage(pixmap);

    //保存原图图片路径 选择路径 +加载文件名+Origion
    if(ConfigData::bSaveOrigion)
    {
        QString strOrigion = ConfigData::imgSavePath+ConfigData::strProtocalName+"/"+"Origion"+"/";
        QDir dir(strOrigion);
        if(!dir.exists())
            dir.mkdir(strOrigion);

        int nid= _MvbTestthread.GetIndex()+1;
        QString strID=QString::number(nid);
        QString strexportFormat =".png" ;
        QString filename = strOrigion+strID+strexportFormat;
        qDebug()<<"origion filename:"<<filename<<endl;
        pixmap.save(filename);
    }

    if(!_bSnapOnly)
    {
//        _MvbTestthread.ReceiveImgRect(ui->labelImgmvb->GetRectImg());
        _MvbTestthread.ReceiveImgRects(ui->labelImgmvb->GetRectImages());
    }

    if(_bSnapOnly)
    {
        _websocketClient->closeWebsocket();
        _bSnapOnly=false;
        ui->btn_snap->setEnabled(true);
        emit SendLogMsg("receive img");

    }
}

void FormMvb::on_btn_configMVB_clicked()
{
    if(_FileclientForm==nullptr)
    {
        _FileclientForm = new FormTcpFileClient();
        _FileclientForm->SetTCPServerInfo(ConfigData::strIP_mvb,ConfigData::strPort_mvb);
    }
    _FileclientForm->show();
}

